﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using Amba.DownloadsCounter.Models;
using Orchard.Data;
using Orchard.Themes;
using Orchard.Mvc.Extensions;

namespace Amba.DownloadsCounter.Controllers
{
    [Themed(false)]
    public class DownloadCounterController : Controller
    {
        private readonly IRepository<DownloadLogRecord> _downloadLogRecordRepo;

        public DownloadCounterController(IRepository<DownloadLogRecord> downloadLogRecordRepo)
        {
            _downloadLogRecordRepo = downloadLogRecordRepo;
        }

        public ActionResult Index(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
                return HttpNotFound();
            var log = new DownloadLogRecord
                {
                    Url = url.Length > 1000 ? url.Substring(0, 1000) : url,
                    LogDate = DateTime.UtcNow
                };

            if (HttpContext.Request != null && HttpContext.Request.UrlReferrer != null)
                log.Referer = HttpContext.Request.UrlReferrer.AbsolutePath;
            _downloadLogRecordRepo.Create(log);
            return this.RedirectLocal("/" + url);
        }
    }
}